package cn.jdemo.juc.thread;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TransmittableThreadLocal -- 阿里的
 *
 * 父子线程传递 - 线程池情况下
 *
 * <a href="https://juejin.cn/post/7064370304595787783"> 源码解释 </>
 */
public class DemoTransParm04 {

    public static void main(String[] args) throws InterruptedException {
        // test01();
        test02();
    }

    /**
     * TransmittableThreadLocal
     *
     * cuurThread_pool-1-thread-1
     * 租户数据1
     * cuurThread_pool-1-thread-1
     * 租户数据2
     */
    public static void test02() throws InterruptedException {
        TransmittableThreadLocal<String> ttl = new TransmittableThreadLocal<>();
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        threadPool = TtlExecutors.getTtlExecutorService(threadPool);//  ttl包装下线程池

        ttl.set("租户数据1");
        threadPool.submit(()->{
            System.out.println("cuurThread_" + Thread.currentThread().getName());
            System.out.println(ttl.get());
        });
        Thread.sleep(10);

        ttl.set("租户数据2");
        threadPool.submit(()->{
            System.out.println("cuurThread_" + Thread.currentThread().getName());
            System.out.println(ttl.get());
        });
    }

    /**
     * 输出内容（首次线程创建可以传递，之后线程复用无法传递）:
     * cuurThread_pool-1-thread-1
     * 租户数据1
     * cuurThread_pool-1-thread-1
     * 租户数据1
     */
    public static void test01() throws InterruptedException {
        ThreadLocal<String> ttl = new InheritableThreadLocal<>();
        ExecutorService threadPool = Executors.newSingleThreadExecutor();// 设置单线程

        ttl.set("租户数据1");
        threadPool.submit(()->{
            System.out.println("cuurThread_" + Thread.currentThread().getName());
            System.out.println(ttl.get());
        });
        Thread.sleep(10);

        ttl.set("租户数据2");
        threadPool.submit(()->{
            System.out.println("cuurThread_" + Thread.currentThread().getName());
            System.out.println(ttl.get());
        });
    }
}
